const UserModel = require('../models/userModel');
const encryption = require('../utils/encryption');
const uModel = new UserModel();

class UserController {
  // 获取用户列表
  async getUsers(ctx) {
    try {
      const users = await uModel.getAllUsers(ctx.query);
      ctx.set('Cache-Control', 'no-cache')
      ctx.body = { code: 200, data: users, message: '用户列表获取成功' };
    } catch (error) {
      ctx.body = { code: 500, message: '用户列表获取失败', error };
    }
  }

  // 添加用户
  async addUser(ctx) {
    const DEF_ACTIVE = 1;
    const DEF_PASSWORD = '123456';
    const { username, fullname, gender, age, role } = ctx.request.body;
    const params = {
      username,
      fullname,
      gender,
      age,
      role,
      password: encryption.hashPassword(DEF_PASSWORD),
      active: DEF_ACTIVE,
      avatar: ''
    };

    try {
      const id = await uModel.addUser(params);

      ctx.set('Content-Type', 'text/html;charset=utf-8');
      ctx.body = { code: 200, data: { id }, message: '添加成功' };
    } catch (error) {
      ctx.set('Content-Type', 'text/html;charset=utf-8');
      ctx.body = { code: 500, message: '添加失败', error };
    }
  }

  // 更新用户
  async updateUser(ctx) {
    try {
      const id = ctx.params.id;
      const { username, fullname, gender, role, age } = ctx.request.body;
      const {affectedRows, userinfo} =
        await uModel.updateUser(id, { username, fullname, gender, role, age });
      
      if (affectedRows > 0) {
        ctx.body = { code: 200, data: userinfo, message: '更新成功' };
      } else {
        ctx.body = { code: 404, message: '用户不存在' };
      }
    } catch (error) {
      ctx.body = { code: 500, message: '更新失败', error };
    }
  }

  // 删除用户
  async deleteUser(ctx) {
    try {
      const id = ctx.params.id;
      const affectedRows = await uModel.deleteUser(id);

      if (affectedRows > 0) {
        ctx.body = { code: 200, message: '删除成功' };
      } else {
        ctx.body = { code: 404, message: '用户不存在' };
      }
    } catch (error) {
      ctx.body = { code: 500, message: '删除失败', error };
    }
  }

  // 上传头像
  async editAvatar(ctx) {
    try {
      const {
        body: { username, fullname, gender, age, avatar },
        // files: { avatar }
      } = ctx.request;

      console.log('头像 avatar', avatar);
      const id = await uModel.addUser({ username, fullname, gender, age, avatar });

      ctx.set('Content-Type', 'text/html;charset=utf-8');
      ctx.body = { code: 200, data: { id }, message: '添加成功' };
    } catch (error) {
      ctx.set('Content-Type', 'text/html;charset=utf-8');
      ctx.body = { code: 500, message: '添加失败', error };
    }
  }
}

module.exports = new UserController();